// 静态资源目录代理
const express = require('express')
const path = require('path')

const resolve = file => path.resolve(__dirname, file)
const config = require(resolve('../config/env'))

const serve = (path, isCache) =>
express.static(resolve(path), {
  maxAge: isCache ? 7 * 24 * 60 * 60 * 1000 : 0 // 静态资源设置缓存一周
})

module.exports = app => {
  if (!config.environment.includes('isLocal')) {
    // 生产环境和测试环境
    app.use(function(req, res, next) {
      // 测试环境 和 cp，直接放行
      if (['shenji.zlketang.com', 'cp.zlketang.com'].includes(req.hostname)) {
        return next()
      }

      // 限制名单，在生产环境下，sem抖音落地页，只允许在 'zlketang.net' 域名下访问
      const restrictedList = ['/wwwpage/dy_promotion.html', '/wwwpage/dy_promotion_link.html']
      if (restrictedList.includes(req.path) && !req.hostname.includes('zlketang.net')) {
        res.redirect(301, '/404')
        return
      }
      
      next()
    })
    app.use('/wwwstatic', serve(resolve('../wwwstatic')))
    app.use('/service-worker.js', serve(resolve('../service-worker.js')))
  } else {
    // 本地环境
    app.use('/dist', serve('../dist')) // 静态资源
    app.use('/wwwstatic', serve('../src/wwwstatic')) // 静态资源 （如：http://localhost:8080/wwwstatic/logo-120.png）
    app.use('/manifest.json', serve('../manifest.json'))
    // app.use('/service-worker.js', serve('../dist/service-worker.js'))
  }
  app.use('/', serve(resolve('../assets'), true))
  // [HuBin] 将/wwwpage设置为静态页面根路径，如在wwwpage下新建test.html，则可通过http://localhost:8080/wwwpage/test.html进行访问
  app.use('/wwwpage', serve(resolve('../wwwpage')))
  app.use('/', serve(resolve('../zl_news_sitemap/sitemap')))
  app.use('/im', serve(resolve('../im'), true))

}
